import 'dart:convert';

import 'package:get/get.dart';
import 'package:getx/config/global/app_cache.dart';
import 'package:getx/models/domain/response/user.dart';
import 'package:getx/router/router_names.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SplashViewModel extends GetxController {
  ///初始化的时候触发
  @override
  void onInit() {
    super.onInit();
  }

  ///构建完第一帧的时候触发
  @override
  void onReady() async {
    super.onReady();

    ///可以从缓存中获取数据
    await loadUserByCache();
  }

  Future<void> loadUserByCache() async {
    SharedPreferences preferences = Get.find<SharedPreferences>();
    String? userCache = preferences.getString('user');
    String? token = preferences.getString('token');
    if (userCache != null && token != null) {
      ///有用户数据缓存
      try {
        User user = User.fromJson(jsonDecode(userCache));
        AppCache appCache = Get.find<AppCache>();
        appCache.user(user);
        appCache.token(token);
        Get.offAllNamed(RouterNames.main);
      } catch (e) {
        preferences.clear();
      }

      ///校验用户数据或token
    } else {
      Get.offAllNamed(RouterNames.login);
    }
  }
}
